package servidorCorba;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.omg.CORBA.ORB;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;
import org.omg.CosNaming.NamingContextPackage.CannotProceed;
import org.omg.CosNaming.NamingContextPackage.InvalidName;
import org.omg.CosNaming.NamingContextPackage.NotFound;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;

import biblioteca.Mensaje;
import biblioteca.UtilidadesBD;

import sGUI.VentanaServidorCorba;


public class ServidorCorba extends IServidorCorbaPOA{

	private static ServidorCorba instance;
	private static VentanaServidorCorba vSC;
	
	private UtilidadesBD BD;
	private static Connection conexionBD = null;
	private Statement stmt;
	private ResultSet rs;
	private int codigo;
	
	private ServidorCorba(){
		
		vSC = new VentanaServidorCorba("127.0.0.1","900","ServidorCorba");
		BD= new UtilidadesBD();
		BD.conectar();
		stmt=BD.getStmt();
		rs=BD.getRs();
				
	}
	
	public static ServidorCorba getInstance() 
	{	
		if(instance == null)
			instance = new ServidorCorba();
		return instance;
	}
	
	
	private void borrarMensaje(int codigo) 
	{
		
		String query ="DELETE FROM TMENSAJE WHERE CODM ="+codigo+";";
		try
		{
			
			stmt = UtilidadesBD.createStatement();
			stmt.executeUpdate(query);
			
		}
		
		catch(SQLException e)
		{

		}
	}


	public void enviarMensaje(String emisor, String destinatario,String asunto, String texto) {
		
		Mensaje m = new Mensaje(emisor,destinatario,asunto,texto);
		guardarMensajeBD(m);
		

	}


	private void guardarMensajeBD(Mensaje m)
	{

		String query = "INSERT INTO TMENSAJE VALUES("+obtenerCodigoMensaje()+",'"+m.getEmisor()+"','"+m.getDestinatario()+"','"+m.getAsunto()+"','"+m.getText()+"');";
		
		try
		{	
			stmt=UtilidadesBD.createStatement();
			stmt.executeUpdate(query);
		}
		
		catch(SQLException e)
		{
			System.out.println(e.getMessage());
		}
		
		vSC.showMessage("nuevo Mensaje para : "+m.getDestinatario()+" insertado en BD");

		
	}

	
	private int obtenerCodigoMensaje()
	{
		
		String query = "SELECT CODM FROM TMENSAJE;";
		int count = 0;
		try
		{
			Statement stmt2=UtilidadesBD.createStatement();
			rs = stmt2.executeQuery(query);
	
			while(rs.next())
			{
				count=rs.getInt(1);
			}
		}
		
		catch (SQLException e)
		{
			System.out.println(e.getMessage());
			
		}
		
		return count+1;
	}
	
	public static void cerrarBD()
	{
		UtilidadesBD.desconectarBD();
	}
	
	public static void stopServer()
	{
		cerrarBD();
		try 
		{
			String[] orb_args = {"-ORBInitialHost","127.0.0.1","-ORBInitialPort","900"};
			ORB orb = ORB.init(orb_args,null);
			org.omg.CORBA.Object nsRef = orb.resolve_initial_references("NameService");
	        NamingContextExt ncRef = NamingContextExtHelper.narrow(nsRef);
	        NameComponent path[];
	        path = ncRef.to_name("ServidorMensajes");
	        ncRef.unbind(path);
		} 
		
		catch (Exception e)
		{
			e.printStackTrace();
		} 
		
        	
	}
	
	public String cargarAsunto(String destinatario)
	{
		String query = "SELECT ASUNTO FROM TMENSAJE WHERE DESTINATARIO = '"+destinatario+"';";
			try {
			
				
				Statement stmt1=UtilidadesBD.createStatement();
				rs = stmt1.executeQuery(query);
				
				rs.next();
				String asunto = rs.getString(1);
//				rs.close();
//				stmt.close();
				return asunto;
				
			} catch (SQLException e) {
//				System.out.println(e.getMessage());
			}
		return "wrongAsunto";
	}


	public String cargarEmisor(String destinatario) {
		String query = "SELECT EMISOR FROM TMENSAJE WHERE DESTINATARIO = '"+destinatario+"';";	
		try {
			Statement stmt3=BD.createStatement();
			rs = stmt3.executeQuery(query);
			
			rs.next();
			String emisor = rs.getString(1);
			return emisor;
			
		} 
		
		catch (SQLException e)
		{
//			System.out.println(e.getMessage());
//			e.printStackTrace();
		}
	return "wrongEmisor";
		
	}


	public String cargarTexto(String destinatario) {
		String query = "SELECT TEXTO FROM TMENSAJE WHERE DESTINATARIO = '"+destinatario+"';";
		
		try {
			Statement stmt5=BD.createStatement();
			
			rs = stmt5.executeQuery(query);
			
			rs.next();
			String texto = rs.getString(1);
			
			return texto;
			
		} catch (SQLException e) {
//			System.out.println(e.getMessage());
		}
	return "wrongTexto";
	}

	public void borrarPorCodigo(String destinatario) {
	
		borrarMensaje(obtenerCodigoMensajeBorrable(destinatario));
	
	}
	
	private int obtenerCodigoMensajeBorrable(String destinatario) {
		String query = "SELECT CODM FROM TMENSAJE WHERE DESTINATARIO ='"+destinatario+"';";
		try {
			stmt=BD.createStatement();
			rs = stmt.executeQuery(query);
			
			rs.next();
			int cod = rs.getInt(1);
			
			
			rs.close();
			stmt.close();
			
			return cod;
			
		} catch (SQLException e) {
//			System.out.println(e.getMessage());
		}
	return 999999;
	}


	public static void main(String []args)
	{
		String[] orb_args = {"-ORBInitialHost","127.0.0.1","-ORBInitialPort","900"};
		ORB orb = ORB.init(orb_args,null);
		try
		{

		org.omg.CORBA.Object ref1 = orb.resolve_initial_references("RootPOA");
		POA poa = POAHelper.narrow(ref1);
		poa.the_POAManager().activate();
		
		ServidorCorba sCorba= new ServidorCorba();
		
		org.omg.CORBA.Object ref2 = poa.servant_to_reference(sCorba);
		IServidorCorba corbaRef = IServidorCorbaHelper.narrow(ref2);
		
		
		org.omg.CORBA.Object ref3 = orb.resolve_initial_references("NameService");
		NamingContextExt ncRef = NamingContextExtHelper.narrow(ref3);
		
		String name = "ServidorMensajes";
		NameComponent[] path = ncRef.to_name("ServidorMensajes");
		ncRef.rebind(path,corbaRef);
		
			
		orb.run();
		
		}
		catch(Exception e){
			System.err.println("Error: "+e);
			e.printStackTrace();
		}
	}







}
